<template>
  <div class="sub-grid">
    <bh-edittable
      ref="table"
      :options="tableOpts"
      :localdata="localData"
      :can-del="canManage"
      @delete="onDel"
      @change="onChange"
    >
    </bh-edittable>
    <bh-button v-if="(!options.readonly) && canManage" class="btn_add" type="link" @click.stop="onAdd">
      新增一行
    </bh-button>
  </div>
</template>

<script>
import { BhEdittable, BhButton } from 'bh-vue'

export default {
  name: 'sub-grid',
  data () {
    return {
      localData: []
    }
  },
  props: {
    item: Object,
    models: Object,
    // datas: Object,
    options: Object,
    // appName: Object
  },
  computed: {
    canManage () {
      return this.metaInfo && this.metaInfo.manageSub === "1"
    },
    columns () {
      const { tableMeta, item } = this
      if (!tableMeta) {
        return []
      }
      const { models } = item.options

      return (models || []).map(item => this.metaMap[item])
    },
    metaMap () {
      return (this.tableMeta || []).reduce((ret, item) => ({
        ...ret,
        [item.name]: item
      }), {})
    },
    metaInfo () {
      const { item, models } = this
      if (!item || !item.options || !item.options.tableName) {
        return null
      }

      const meta = models.meta || []
      const tableName = item.options.tableName
      for (let i = 0; i < meta.length; i++) {
        if (meta[i] && meta[i].name === tableName) {
          return meta[i]
        }
      }

      return null
    },
    tableMeta () {
      const { item, models } = this
      if (!item || !item.options || !item.options.tableName) {
        return []
      }

      const meta = models.meta || []
      const tableName = item.options.tableName
      for (let i = 0; i < meta.length; i++) {
        if (meta[i] && meta[i].name === tableName) {
          const subMetas = meta[i].ref || []

          return subMetas.map(element => {
            const newItem = { ...element }
            if(!newItem.caption) {
              newItem.caption = newItem.name
            }

            if (newItem.url) {
              const dicId = newItem.url ? newItem.url.match(/\/dic\/(\S*).do/)[1] : ''
              const thirdParams = newItem.url ? "sign=" + models.supportSigns[dicId] + "&time=" + models.time : ''
              if (thirdParams && newItem.url.indexOf(thirdParams) === -1) {
                newItem.url = newItem.url + "?" + thirdParams
              }
            }

            return newItem
          })
        }
      }
      return null
    },
    tableOpts () {
      return {
        // localdata: this.localData,
        columns: this.columns,
        readonly: this.options.readonly
      }
    },
  },
  methods: {
    onAdd () {
      this.localData.push({})
      // this.$refs.table.toAddRows({})
    },
    onDel (row, index) {
      if (this.localData) {
        this.localData.splice(index, 1)
        Vue.nextTick(() => {
          this.emitChange()
        })
        // this.$refs.table.deleteByRowNum(index)
        //新加的删除方法
        this.$refs.table.toDelRows(index)
        // console.log(this.$refs.table.getTotalRecords(),"全部数据")
         
      }
    },
    onChange (e) {
      this.emitChange(e, this.tableMeta)
    },
    emitChange (e, tableMeta) {
      Vue.nextTick(() => {
        // console.log('sub grid emit change')
        const data = this.getValue()
        // this.$emit('change', data)
        this.$emit('sublist-change', data, e, tableMeta)
      })
    },
    getValue () {
      return {[this.item.options.tableName]: this.$refs.table.getTotalRecords()}
    },
    setValue (val) {
      this.localData = val && val[this.item.options.tableName] || []
      // console.log(' sub grid set val', this.localData)
    },
    // formChange (e) {
    //   this.$emit("change",e)
    // },
    validate () {
      return this.$refs.table.validate()
    }
  },
  // mounted () {
  //   this.$nextTick(() => {
  //     console.log('grid mounted')
  //   })
  // },
  components: {
    BhEdittable,
    BhButton,
  }
}
</script>

<style lang="less" scoped>
  .sub-grid {
    margin-bottom: 12px;
  }
  .btn_add {
    background: none;
    box-shadow: none;
    margin-top: 4px;
    text-decoration: none;
  }
</style>
